//
//  TJPullDownRefreshControl.swift
//  TJSinaWeibo
//
//  Created by 唐后能 on 16/4/16.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit

// 刷新控件的高度.
private let TJRefreshControlHeight:CGFloat = 60

// 刷新控件显示的3种状态.
private enum TJRefreshControlStatus:Int {

    case Normal = 1 //箭头向下,下拉刷新.
    case PullRefresh = 2 //箭头向上,释放刷新.
    case Refreshing = 3 //正在刷新...
}

class TJPullDownRefreshControl: UIView {

    // 定义父控件属性.
    private var superScrollView:UIScrollView?
    
    // 定义闭包.
    var refreshHander:(()->())?
    
    // 定义刷新类型.
    private var status:TJRefreshControlStatus = TJRefreshControlStatus.Normal {
    
        didSet {
        
            switch status {
            
            case .Normal :
                // 显示箭头,隐藏转轮.
                arrorView.hidden = false
                rotationView.hidden = true
                
                // 将文字改为 "下拉刷新"
                contentLabel.text = "下拉刷新"
                // 恢复transform.
                UIView.animateKeyframesWithDuration(0.25, delay: 0, options: [], animations: { () -> Void in
                    
                    self.arrorView.transform = CGAffineTransformIdentity
                    }, completion: nil)
                // 将refreshControl隐藏回去.-->要从refreshing到normal才退回去.
//                UIView.animateWithDuration(0.25, animations: { () -> Void in
//                    self.superScrollView!.contentInset.top -= TJRefreshControlHeight
//                })
                
            case .PullRefresh:
//
                // 将文字改为 "释放刷新"
                contentLabel.text = "释放刷新"
                // 箭头旋转180度
                UIView.animateKeyframesWithDuration(0.25, delay: 0, options: [], animations: { () -> Void in
                    
                    self.arrorView.transform = CGAffineTransformRotate(self.arrorView.transform, CGFloat(M_PI) - 0.001)
                    }, completion: nil)
            case .Refreshing:
                // 显示转轮,隐藏箭头.
                arrorView.hidden = true
                rotationView.hidden = false
                
                // 将文字改为:"正在刷新"
                contentLabel.text = "正在刷新"
                
                // 旋转转轮.
                let anima = CABasicAnimation(keyPath: "transform.rotation")
                anima.toValue = M_PI * 2
                anima.duration = 1
                anima.repeatCount = MAXFLOAT
                anima.removedOnCompletion = false
                // 添加key可以防止动画叠加.
                rotationView.layer.addAnimation(anima, forKey: "anima")

                // 需要将刷新的控件显示出来.
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.superScrollView!.contentInset.top += TJRefreshControlHeight
                })
                
                // 调用闭包,刷新数据.
                refreshHander?()
            }
        }
    }
    
    // MARK - 提供给外界的接口.
    // 开始刷新.
    func startRefresh(){
    
        status = .Refreshing
    }
    // 完成刷新.
    func endRefresh(){
    
        // 从refreshing切换到normal状态.
        status = .Normal
        // 将refreshControll退回去.
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            self.superScrollView!.contentInset.top -= TJRefreshControlHeight
        })
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        let frameInSuperView = CGRectMake(0, -TJRefreshControlHeight, UIScreen.mainScreen().bounds.width, TJRefreshControlHeight)
        super.init(frame: frameInSuperView)
        setupUI()
        backgroundColor = UIColor.brownColor()
    }
    
    // 添加子控件.
    private func setupUI(){
    
        // 1,添加子控件.
        addSubview(arrorView)
        addSubview(rotationView)
        addSubview(contentLabel)
        
        // 开始默认隐藏转轮.
        rotationView.hidden = true
        
        // 2,添加约束.
        // 箭头.
        arrorView.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(-30)
        }
        
        // 转轮.
        rotationView.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(-30)
        }
        
        // 文字.
        contentLabel.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(30)
        }
            
    }
    
    
    // MARK - 获取父控件.
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        if let scrollView = newSuperview as? UIScrollView {
            superScrollView = scrollView
            
            // 注册对父控件contentOffset.y属性的监听.
            superScrollView?.addObserver(self, forKeyPath: "contentOffset", options: [], context: nil)
        }
    }
    
    // 移除KVO监听.
    deinit{
        
        removeObserver(self, forKeyPath: "contentOffset")
    }
    
    // 实现KVO的监听方法.
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        TJPrint("tableView滚动情况:\(superScrollView?.contentOffset.y)")
        if (superScrollView?.dragging)!  {
        
            if superScrollView?.contentOffset.y > -((superScrollView?.contentInset.top)! + TJRefreshControlHeight)  && status == .PullRefresh {
//                TJPrint("切换到Normal")
                status = .Normal
            }else if superScrollView?.contentOffset.y <= -((superScrollView?.contentInset.top)! + TJRefreshControlHeight) && status == .Normal {
//                TJPrint("切换到PullRefresh")
                status = .PullRefresh
            }
        }else if status == .PullRefresh { //松开手,且正处于释放刷新状态.
        
            TJPrint("切换到refreshing")
            status = .Refreshing
        }
    }
    
    
    // MARK - 懒加载子控件.
    // 箭头.
    private lazy var arrorView:UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    // 转轮.
    private lazy var rotationView:UIImageView = UIImageView(image: UIImage(named: "tableview_loading"))
    
    // 文字.
    private lazy var contentLabel:UILabel = {
    
        let label = UILabel()
        // 设置.
        label.textColor = UIColor.darkGrayColor()
        label.font = UIFont.systemFontOfSize(14)
        label.text = "下拉刷新"
        label.sizeToFit()
        
        return label
    }()

}
